<?php
/**
 * Created by PhpStorm.
 * User: ytlmi
 * Date: 2018/2/3
 * Time: 14:33
 */

namespace app\lab\controller;

use app\common\controller\BaseController;
use app\lab\model\Frequency as FrequencyM;
use app\common\commonClass\ExcelImportTool;

class Frequency extends BaseController
{
    protected $model = 'app\lab\model\Frequency';

    //获取现有的全部基因频率库名称
    public function getFrequencyList()
    {
        $m = new FrequencyM();
        return array_values(array_unique($m->column('name')));
    }

    //获取一个频率库的全部频率
    public function getFullFrequency($name)
    {
        try {
            $m = new FrequencyM();
            $data = $m->where('name', $name)->select();
            if (!is_array($data)) return '频率库不存在';
            $arr_frequency = [];
            foreach ($data as $item) {
                $arr_frequency[$item->marker][$item->allele] = $item->frequency;
            }
            return $arr_frequency;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    //获取频率库包含的基因座
    public function getAllMarker($name)
    {
        $m = new FrequencyM();
        return array_unique($m->where('name', $name)->column('marker'));
    }

    //获取单个基因座的频率
    public function getByMarker($name, $marker)
    {
        $m = new FrequencyM();
        return $m->where('name', $name)->where('marker', $marker)->column('allele,frequency');
    }

    //获取单个allele的频率
    public function getByAllele($name, $marker, $allele)
    {
        $m = new FrequencyM();
        return $m->where('name', $name)->where('marker', $marker)->where('allele', $allele)->value('frequency');
    }

    //获取全部突变率
    public function getAllMut($name)
    {
        try {
            $m = new FrequencyM();
            $data = $m->where('name', $name)->select();
            $arr_mutation = [];
            foreach ($data as $item) {
                if ($item->mutation && $item->mutation != '') {
                    $arr_mutation[$item->marker] = $item->mutation;
                }
            }
            return $arr_mutation;
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    //获取单个基因座的突变率
    public function getMutByMarker($name, $marker)
    {
        $m = new FrequencyM();
        return $m->where('name', $name)->where('marker', $marker)->value('mutation');
    }

    /**
     * 导入频率表
     * @return mixed
     */
    public function uploadFrequency()
    {
        $header = [
            'name' => '名称',
            'marker' => '基因座',
            'allele' => '等位基因',
            'frequency' => '频率',
            'mutation' => '突变率'
        ];

        $construct = [
            'name' => [
                'marker' => [
                    'mutation' => 'mutation',
                    'allele' => 'frequency'
                ]
            ]
        ];

        $alwaysRequire = ['name', 'marker', 'allele', 'frequency', 'mutation'];

        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file('file');
        // 移动到框架应用根目录/public/uploads/ 目录下
        try {
            if ($file) {
                //保存文件
                $savePath = $_SERVER['DOCUMENT_ROOT'] . DS . 'uploads' . DS . 'xls';
                $info = $file->move($savePath);
                $filePath = $savePath . DS . $info->getSaveName();
                //验证并格式化数据
                $result = ExcelImportTool::instance($filePath)->header($header, $construct)->check($alwaysRequire)->originalData();
                foreach ($result as $key => $item) {
                    $result[$key]['frequency'] = sprintf("%.4f", $item['frequency']);
                    if (preg_match('/\./', $item['allele'])) {
                        $result[$key]['allele'] = sprintf("%.1f", $item['allele']);
                    }
                }
                //存储
                $this->M->saveAll($result);
                return true;
            } else {
                return false;
            }
        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    public function downloadFrequency($freName)
    {
        $freData = $this->getFullFrequency($freName);
        $mutData = $this->getAllMut($freName);
        $fileName = $_SERVER['DOCUMENT_ROOT'] . DS . 'table' . DS . iconv('UTF-8', 'GB2312//IGNORE', $freName) . '.csv';
        $file = fopen($fileName, 'wb');
        fwrite($file, iconv('UTF-8', 'GB2312//IGNORE', '名称,基因座,等位基因,频率,突变率') . "\n");
        foreach ($freData as $marker => $arr) {
            $mut = isset($mutData[$marker]) ? $mutData[$marker] : '';
            foreach ($arr as $allele => $fre) {
                fwrite($file, iconv('UTF-8', 'GB2312//IGNORE', $freName) . ',' . $marker . ',' . $allele . ',' . $fre . ',' . $mut . "\n");
            }
        }
        fclose($file);
        $this->redirect('/table/' . iconv('UTF-8', 'GB2312//IGNORE', $freName) . '.csv');
    }

}